import os
import sys
import subprocess
from PySide6.QtGui import QBrush,QColor
from PySide6.QtCore import (Slot,Qt,QAbstractTableModel)
from PySide6.QtWidgets import (
    QTableView,
    QTableWidget,
    QPushButton,
    QTableWidgetItem,
    QDialog,
    QLabel,
    QTableWidgetSelectionRange)
from PySide6.QtUiTools import QUiLoader
from MyConfig import MyConfig
from GuidsSync import Synchronizer
import pandas as pd
from ExcelPath import ExcelPath

class TableModel(QAbstractTableModel):
    def __init__(self, data:pd.DataFrame):
        super(TableModel, self).__init__()
        self._data = data

    def data(self, index, role):
        if role == Qt.DisplayRole:
            value = self._data.iloc[index.row(), index.column()]
            return str(value)

    def rowCount(self, index):
        return self._data.shape[0]

    def columnCount(self, index):
        return self._data.shape[1]

    def headerData(self, section, orientation, role):
        # section is the index of the column/row.
        if role == Qt.DisplayRole:
            if orientation == Qt.Horizontal:
                return str(self._data.columns[section])

            if orientation == Qt.Vertical:
                return str(self._data.index[section])

class GuidsWindow(QDialog):
    
    normalButtonColor  = "background-color: rgb(236, 236, 236);"
    warningButtonColor = "background-color: rgb(255, 179, 48);"
    warningBrush:QBrush = QBrush(QColor("darkCyan"),bs=Qt.BrushStyle.SolidPattern)
    
    
    def __init__(self) -> None:
        try:
            try:
                self.cur_path = sys._MEIPASS
            except:
                self.cur_path = os.path.dirname(os.path.realpath(__file__))   
            super().__init__()
            self.guids_changed = False
            loader = QUiLoader()
            
            # init config
            self.settings = MyConfig(f"{self.cur_path}\\config.json")
            self.guidsDir:str = self.settings.get("GuidsDir_",defaultValue=f"{self.cur_path}\\guids") #bug fix GuidsDir -> GuidsDir_
            self.RemoteGuidsDir:str = self.settings.get("RemoteGuidsDir",defaultValue=None)
            # self.ExcelPath:str = self.settings.get("ExcelPath",defaultValue=None)
            ## issue http://vsys01775:8282/flea/pyexcelcons3/-/issues/8
            self.ExcelPath:str = ExcelPath.get()
            
            # init components
            self.GuidsDialog:QDialog = loader.load(f"{self.cur_path}\\GuidsWindow.ui", None)
            self.remoteGuidsButton:QPushButton = self.GuidsDialog.remoteGuidsButton
            self.localGuidsButton:QPushButton = self.GuidsDialog.localGuidsButton
            self.syncWarningLabel:QLabel = self.GuidsDialog.syncWarningLabel
            self.guidsTable:QTableWidget = self.GuidsDialog.guidsTable
            self.dataView:QTableView = self.GuidsDialog.dataView
            
            # init slot connections
            self.remoteGuidsButton.clicked.connect(self.remoteGuidsButton_clicked)
            self.localGuidsButton.clicked.connect(self.localGuidsButton_clicked)
            self.guidsTable.itemSelectionChanged.connect(self.guid_select)
            
                       
            # load guids
            self.sync:Synchronizer = None
            self.reload_guids()
                
        except : raise 
    
    def show(self):
        try:
            self.GuidsDialog.exec()
        except: raise
    
    def dialog_accepted(self):
        print("accepted")
    
    def init_sync(self):
        try:
            self.sync = Synchronizer(self.RemoteGuidsDir,self.guidsDir)
            self.syncWarningLabel.setVisible(False)              
        except Exception as exp: 
            if str(exp)=="Bad repo":
                self.syncWarningLabel.setVisible(True)
                pass
            else:
                raise exp 
           
    def remoteGuidsButton_clicked(self):
        """ Получить файлы с сервера """
        try:
            if self.sync.local_files_empty: self.sync.init_local()
            else: 
                self.sync.sync_server()
                self.guids_changed = True
            self.reload_guids()
        except: raise
    
    def localGuidsButton_clicked(self):
        """ Отправить файлы на сервер """
        try:
            self.sync.sync_local()
            self.reload_guids()
        except: raise
    
    @Slot()
    def open_excel(self):
        """Открыть excel-файл\n
            Путь к excel.exe должен быть указан в config.json в секции ExcelPath
        """
        try:
            btn:QPushButton = self.sender()
            cmd  = btn.property("cmd")
            print(cmd)
            # res = os.system(cmd)
            res = subprocess.run([self.ExcelPath,cmd],check=True)
            print(f"result: {res.returncode}")
            if res.returncode==0: self.reload_guids()
            if self.sync.newer_local_exist: self.guids_changed = True
        except: raise
            
    def reload_guids(self):
        """ Перезагрузить список справочников """
        try:
            self.init_sync()
            self.guidsTable.setColumnWidth(0,310)
            self.guidsTable.setColumnWidth(1,20)
            self.guidsTable.setColumnWidth(2,20)
            self.guidsTable.setColumnWidth(3,20)                        
            self.guidsTable.clearContents()
            self.guidsTable.setRowCount(0)
            for key in self.sync.local_files.files.keys():
                row = self.guidsTable.rowCount()
                self.guidsTable.insertRow(row)
                self.guidsTable.setItem(row,0,QTableWidgetItem(key))
                btn:QPushButton = QPushButton(self.guidsTable)
                fullPath = os.path.abspath(f"{self.guidsDir}\\{key}")
                cmd = f'{fullPath}'
                btn.setProperty("cmd",cmd)
                btn.setText("...")
                btn.clicked.connect(self.open_excel)
                self.guidsTable.setCellWidget(row,3,btn)
                                
                if key in self.sync.newer_server.keys():
                    twi1 =QTableWidgetItem(" ")
                    twi1.setBackground(self.warningBrush)
                    self.guidsTable.setItem(row,1,twi1)                     
                if key in self.sync.newer_local.keys():
                    twi2 =QTableWidgetItem(" ")
                    twi2.setBackground(self.warningBrush)                    
                    self.guidsTable.setItem(row,2,twi2)
               
            if self.sync.newer_server_exist: self.remoteGuidsButton.setStyleSheet(self.warningButtonColor)
            else: self.remoteGuidsButton.setStyleSheet(self.normalButtonColor)
            if self.sync.newer_local_exist: self.localGuidsButton.setStyleSheet(self.warningButtonColor)
            else: self.localGuidsButton.setStyleSheet(self.normalButtonColor)
            if self.sync.local_files_empty and not self.sync.server_files_empty: self.remoteGuidsButton.setStyleSheet(self.warningButtonColor)            
        except: raise
        
    @Slot()
    def guid_select(self):
        """ Выбор справочника """
        try:
            table:QTableWidget = self.sender()
            selectedRange = table.selectedRanges()
            if selectedRange is not None and selectedRange.__len__()>0 :
                selected:QTableWidgetSelectionRange = selectedRange[0] 
                item = table.item(selected.topRow(),0)
                if item is not None:
                    file=f"{self.guidsDir}\\{item.data(0)}"
                    print(file)
                    df = pd.read_excel(file)
                    model = TableModel(df)
                    self.dataView.setModel(model)
            
        except: raise